import {Map, View, Image} from '@tarojs/components'
import Taro from '@tarojs/taro';
import {connect} from '@tarojs/redux';
import {request, unite, appConfig} from "../../../utils/index";
import './selectMap.scss';
import Go from "../../../asset/images/go.png";
import Flag from "../../../asset/images/flag.png";
import Point from "../../../asset/images/point.png";
import Hui from "../../../asset/images/hui.png";
import none from "../../../asset/images/none.png";
import Home from "../../../asset/images/home.png";
import search from "../../../asset/images/search_icon.png";

class MapBox extends Taro.Component {
    config = {
        navigationStyle:'custom',
    };

    state = {
        latitude: 0, //经度
        longitude: 0, //纬度
        adcodes: 0, //地址名称

        classDate: '', //课程日期，格式yyyy/mm/dd
        classScaleId: -1, //团课规模ID
        classTypeId: -1, //课程类型ID
        periodId: -1, //时间段区间ID
        priceId: -1, //	价格区间ID
        regionId: 340102, //区域ID

        markers:[], //map组件markers的参数
        id: null, //选取教室id
        listDataWrap: [],
        listData: [], //列表数据
        is_type: false, //false 回弹列表 true 打开列表
        roomListData: [], //课程列表
    };

    temp = {
        loading: false //防止多次点击
    };

    componentWillMount() {
        const option = this.$router.params;
        const {map, regionIds, setClassDate} = this.props;
        console.log(option.timer);
        this.setState({
            latitude: option.latitude || map.latitude, //赋值经度
            longitude: option.longitude || map.longitude, //赋值纬度
            adcodes: option.adcode, //赋值地址名称
            regionId: option.regionId || regionIds,
            classDate: option.timer || setClassDate, //初始化课程需要初始时间
        },()=>{
            this.init();
        })
    };

    //在 componentWillMount后执行
    componentDidMount() {
        //创建 map 上下文 MapContext 对象
        this.mapCtx = Taro.createMapContext("shopMap");
    };

    //获取商家位置
    init = () => {
        const {classScaleId, classTypeId, periodId, priceId, regionId, latitude, longitude} = this.state;
        if (this.temp.loading) return; //防止多次点击
        this.temp.loading = true;
        const params = {
            url: '/wx/firstPage/getNearByRoomList',
            data:{
                classScaleId, //团课规模ID
                classTypeId, //课程类型ID
                distance: '10', //与当前位置距离（单位km）
                latitude,
                longitude,
                periodId, //时间段区间ID
                priceId, //价格区间ID
                regionId, //区域ID
                queryType: 2, //根据区域ID查询的时候为1，根据经纬度查询的时候为2）
            }
        };
        request(params, false).then(res => {
            this.temp.loading = false; //防止多次点击
            if (res) {
                if (res.code == 200) {
                    Taro.hideLoading();
                    if (res && res.data) {
                        let ary = [];
                        if (res.data.length != 0) {
                            ary = res.data.map((item) => {
                                let maker = {
                                    alpha: "1", //标注的透明度
                                    height: 40, //标注图标高度
                                    width: 40, //标注图标宽度
                                    // iconPath: flag,
                                    iconPath: 'https://pic.pmad.com.cn/healthy/class/%E9%97%A8%E5%BA%97%E5%AE%9A%E4%BD%8D.png', //显示的图标   true的都为C享
                                    label:{
                                        anchorX: -24, //label的坐标，原点是 marker 对应的经纬度
                                        anchorY: 1, //label的坐标，原点是 marker 对应的经纬度
                                        bgColor: "#fff", //背景色
                                        borderColor: "#494948", //边框颜色
                                        borderRadius: 2, //边框圆角
                                        borderWidth: 1, //边框宽度
                                        color: "#676765", //文本颜色
                                        fontSize: 10, //文字大小
                                        padding: 2, //文本边缘留白
                                        textAlign: "center" //文本对齐方式。有效值: left, right, center
                                    }
                                };
                                maker.label.content = item.roomName; //文本(商店名称)
                                maker.id = item.roomId; //标记点 id
                                maker.latitude = item.latitude; //店铺经度
                                maker.longitude = item.longitude; //店铺维度
                                maker.address = item.address;
                                maker.avatar = item.avatar;
                                return maker;
                            });
                            this.setState({
                                markers: ary,
                                listDataWrap: res.data,
                                id: res.data[0].roomId,
                            },() => {
                                this.markerTap({markerId: res.data[0].roomId})
                            })
                        } else {
                            this.setState({
                                markers: ary,
                                listDataWrap: res.data,
                                id: null
                            })
                        }
                    }
                }
            }
        })
    };

    //点击跳转到相对应的店铺
    markerTap = e => {
        console.log(JSON.stringify(e) + 'zhao');
        const {listDataWrap} = this.state;
        const option = this.$router.params;
        let data = [];
        listDataWrap.forEach((item) => {
            if (item.roomId == e.markerId) {
                data = {
                    avatar: item.avatar, //教室图片
                    roomName: item.roomName, //教室名称
                    address: item.address, //地址
                    describeInfo: item.describeInfo,//教室介绍
                    id: item.roomId,
                    collectionStatus: item.collectionStatus, //收藏状态（0 未收藏、1 已收藏）
                    latitude: item.latitude,
                    longitude: item.longitude,
                }
            }
        });
        this.setState({
            classDate: option.timer,
            id: e.markerId,
            listData: data,
        })
    };

    markerTapSkip = (e) => {
        Taro.redirectTo({url: '../arranging-coursey-next/arrangingCourseyNext?id=' + this.$router.params.id+'&roomId='+e.markerId})
    };

    getTypes = (item) => {
        console.log('zhao');
        const {regionId} = this.state;
        this.setState({
            classScaleId: Number(item.selectList) || -1, //1v1
            periodId: Number(item.tgTypeId) || -1, //时间段
            regionId: Number(item.regionId) || regionId, //地区
            classTypeId: Number(item.classTypeId) ||-1, //课程类型
            priceId: Number(item.moneyId) || -1, //价格id
            id: null,
        }, () => {
            this.init() //获取课程列表
        })
    };

    //跳转到教室详情页
    skipDetail = () => {
        Taro.navigateTo({
            url: '../classroom-detail/classroomDetail?id=' + this.state.id
        })
    };

    //跳转教室地图导航
    goToMap = (e) => {
        e.stopPropagation(); //防止父级点击事件干扰
        const {listData} = this.state;
        console.log(listData);
        if (listData.latitude) {
            Taro.openLocation({
                latitude: Number(listData.latitude),
                longitude: Number(listData.longitude),
                name: listData.roomName,
                address: listData.address
            })
        } else {
            unite.showToast('该店铺暂无经纬度');
        }
    };

    //收藏 取消收藏
    collect = () => {
        const {listData} = this.state;
        if (listData.collectionStatus == 0) {
            const params = {
                url: '/wx/collection/save',
                data:{
                    collectionTypeCode: '03', //收藏类型编码 （01 课程收藏、02 教练收藏、03 教室好收藏）
                    relateKeyId: listData.id,
                }
            };
            request(params).then(res => {
                if (res) {
                    if(res.code == 200) {
                        this.setState(prevState => {
                            listData.collectionStatus = 1;
                            return{
                                listData: prevState.listData
                            }
                        })
                        unite.showToast('收藏成功');
                        this.init() //获取课程列表
                    }
                }
            })
        } else {
            const params = {
                url: '/wx/collection/deleteById',
                data:{
                    collectionTypeCode: '03', //收藏类型编码 （01 课程收藏、02 教练收藏、03 教室好收藏）
                    relateKeyId: listData.id,
                }
            };
            request(params).then(res => {
                if (res) {
                    if(res.code == 200) {
                        this.setState(prevState => {
                            listData.collectionStatus = 0;
                            return{
                                listData: prevState.listData
                            }
                        })
                        unite.showToast('已取消收藏');
                        this.init() //获取课程列表
                    }
                }
            })
        }
    };

    // //回归原来的位置
    clickcontrol = () => {
        const option = this.$router.params;
        this.setState({
            latitude: option.latitude, //赋值经度
            longitude: option.longitude, //赋值纬度
            adcode: option.adcode //赋值地址名称
        },()=>{
            let ctx = Taro.createMapContext("shopMap");
            ctx.moveToLocation();
            this.init();
        })
    };

    skipIndex = () => {
        Taro.navigateBack({
            delta: 1
        })
    };

    // 移动地图重新获取附近商家
    regionchange = e => {
        console.log(e)
        // 地图发生变化的时候，获取中间点，也就是用户选择的位置toFixed   
        if (e.type == 'end' && e.causedBy == 'drag') {
            this.mapCtx.getCenterLocation({
                type: 'gcj02',
                success: (res) => {
                    if(res.latitude === this.state.latitude && res.longitude === this.state.longitude) return;
                    this.setState({
                        latitude: res.latitude,
                        longitude: res.longitude,
                    },()=>{
                        Taro.showLoading({
                            title: '加载中…'
                        });
                        this.init();
                    })
                }
            })
        }
    };

    render() {
        const {latitude, longitude, markers, id, listData, is_type, roomListData, classDate} = this.state;
        const {} = this.props;
        return (
            <View>
                {!is_type &&(
                    <Map
                        id="shopMap"
                        className="shop-map"
                        latitude={latitude} //当前经度
                        longitude={longitude} //当前纬度
                        markers={markers} //标记点
                        scale={13}
                        showLocation //显示带有方向的当前定位点
                        // includePoints={markers}
                        onMarkerTap={this.markerTapSkip} //点击标记点时触发
                        onLabelTap={this.markerTapSkip}//点击label点时触发
                        onRegionChange={this.regionchange} //视野发生变化时触发
                    />
                )}
                <View className="course-head">
                    <View className="head-top" style={'height:' + (Taro.getSystemInfoSync()['statusBarHeight']+43) + 'px;'}>
                        <Image className="head-img-return" src={Home} mode="widthFix" onClick={this.skipIndex}/>
                    </View>
                    <View className="search-content flex-lr" style={'margin-top:' + (Taro.getSystemInfoSync()['statusBarHeight']+50) + 'px;'}>
                        <View className="flex-l">
                            <Image className="search-icon" src={search} mode="widthFix"/>
                            <View>课程 / 地点 / 瘦身塑形</View>
                        </View>
                    </View>
                </View>
                <View className="shop-sort">
                    {!is_type &&(
                        <View className="restore-site">
                            <View className="restore-site-wrap" onClick={this.clickcontrol}>
                                <Image className="site-img" src={Hui}/>
                            </View>
                        </View>
                    )}
                    <View className="shop-sort-wrap">
                        {id != null && listData &&(
                            <View className="shop-sort-top">
                                <View className="shop-sort-content flex-l" onClick={this.skipDetail}>
                                    <View className="shop-sort-heng"></View>
                                    <View className="shop-sort-titles">教室列表</View>
                                </View>
                            </View>
                        )}
                        <View className="markers-list-wrap">
                            {markers && markers.map((item, index) => (
                                <View className="markers-list flex-lr" key={index} onClick={() => { Taro.redirectTo({url: '../arranging-coursey-next/arrangingCourseyNext?id=' + this.$router.params.id+'&roomId='+item.id})}}>
                                    <Image className="shop-sort-img" src={item.avatar} mode="widthFix"/>
                                    <View className="shop-sort-title">
                                        <View className="shop-sort-name">{item.label.content}</View>
                                        <View className="shop-sort-address">{item.address}</View>
                                    </View>
                                </View>
                            ))}
                        </View>
                        {(!markers || markers.length == 0) &&(
                            <View className="none">
                                <Image src={none}/>
                                <View>暂无教室</View>
                            </View>
                        )}
                    </View>
                </View>
            </View>

        )
    }
}

const mapStateToProps = state => {
    let {mallCategory, map, regionIds, setClassDate} = state;
    return {
        mallCategory,
        map,
        regionIds,
        setClassDate,
    }
};

export default connect(mapStateToProps, null)(MapBox);

